<template>
  <div class="jsonutil-wrapper">
    <div class="tool-box">
      <Button type="primary" shape="circle" class="btn-item" @click="handle">JSON格式化</Button>
      <Button type="primary" shape="circle" class="btn-item" @click="clearAll">清空输入</Button>
    </div>
    <div class="demo-split">
      <Split v-model="split">
        <div slot="left" class="demo-split-pane">
          <Input v-model="value" type="textarea" placeholder="请输入JSON字符串" />
        </div>
        <div slot="right" class="demo-split-pane">
          <json-viewer
            :value="jsonData"
            :expand-depth=5
            copyable
            boxed
            expanded
            class="json-edit"
          >
          </json-viewer>
        </div>
      </Split>
    </div>
  </div>
</template>

<script>
import jsonlint from 'jsonlint'
export default {
  name: 'JsonUtil',
  data(){
    return {
      jsonData: {
        title: '示例结果',
        id: 1000,
        data: [
          {
            name:'test1',
            age:18
          },
          {
            name:'test2',
            age:20
          }
        ]
      },
      value: '',
      split: 0.4
    }
  },
  methods:{
    handle(){
      if(this.value.length <= 0){
        this.$Message.warning('请先输入JSON字符串！')
        return
      }
      try {
        let object = jsonlint.parse(this.value)
        if(object){
          this.jsonData = object
        }
      } catch (error) {
        this.jsonData = error.message
      }
    },
    /**
     * 清空输入
     */
    clearAll(){
      this.value = ''
    }
  }
}
</script>

<style lang="less" scoped>
.jsonutil-wrapper{
  max-width: 1280px;
  margin: 0 auto;
  .demo-split{
    height: ~"calc(100vh - 200px)";
    .demo-split-pane{
      .json-edit{
        height: ~"calc(100vh - 200px)";
        overflow: auto;
      }
    }
  }
  .tool-box{
    width: 100%;
    height: 50px;
    padding: 10px;
    text-align: right;
    .btn-item{
      margin-left: 10px;
    }
  }
}
</style>

<style scoped>
.demo-split-pane >>> textarea.ivu-input{
  height: calc(100vh - 199px);
  resize: none;
}
</style>
